<template>
  <div class="add-file-analysis-task">
    <ContentWrap :bodyStyle="{ paddingTop: '5px' }">
      <back :backOption="backOption" />
      <!-- 表单 -->

      <div class="h-full">
        <el-form
          @submit.prevent
          scroll-to-error
          label-width="180px"
          ref="ElForm"
          label-suffix="："
          :rules="rules"
          :model="formData.data"
        >
          <h3 class="m-section-title">
            <span class="m-section-title__text">任务基本信息</span>
          </h3>
          <el-form-item label="任务名称" prop="name" class="col-item">
            <ns-input
              :rows="6"
              type="text"
              v-model.trim="formData.data.name"
              placeholder="请输入任务名称"
              style="width: 50%"
              clearable
              :maxlength="50"
            />
          </el-form-item>
          <el-form-item label="出境批次" prop="batchNumVO" class="batch-num">
            <el-select-v2
              placeholder="请选择出境批次"
              clearable
              v-model="formData.data.batchNumVO"
              :options="exitBatch"
              :props="batchProps"
              :loading="batchLoading"
              @change="handleBatchChange"
              class="mr-50%"
            />
            <div class="exit-batch-info mb-0px" v-if="formData.data.batchNumVO">
              <span class="pr-16px">
                <span class="text-info">联系人: </span>
                <span>{{ currentBatch?.linkName }}</span>
              </span>
              <span class="pr-16px">
                <span class="text-info">单位名称: </span>
                <span>{{ currentBatch?.unitName }}</span>
              </span>
              <span class="pr-16px">
                <span class="text-info">联系方式: </span>
                <span>{{ currentBatch?.linkWay }}</span>
              </span>
              <span class="pr-16px">
                <span class="text-info">接收者名称: </span>
                <span>{{ currentBatch?.receiverName }}</span>
              </span>
              <p class="my-0">
                <span class="text-info">出境场景描述: </span>
                <span>{{ currentBatch?.sceneDesc }}</span>
              </p>
            </div>
          </el-form-item>
          <el-form-item label="归属机构:" prop="deptId">
            <el-cascader
              ref="deptCascader"
              v-model="formData.data.deptId"
              @change="handleDeptChange"
              placeholder="请选择归属机构"
              :props="formData.cascaderProps"
              :options="formData.deptList"
              filterable
              clearable
              value-on-clear=""
              :filter-method="sysFilterMethod"
            />
          </el-form-item>
          <el-form-item label="归属系统:" prop="sysId">
            <el-cascader
              @change="handleSystemChange"
              ref="systemCascader"
              v-model="formData.data.sysId"
              placeholder="请选择归属系统"
              :props="formData.systemCascaderProps"
              :options="formData.systemList"
              filterable
              clearable
              value-on-clear=""
              :filter-method="sysFilterMethod"
            />
          </el-form-item>
          <el-form-item style="margin-bottom: 10px">
            <Icon icon="svg-icon:tips" />
            <span style="color: #cccccc">归属机构与归属系统至少填写一项</span>
          </el-form-item>
          <el-form-item label="数据标准" prop="dataStandardId" class="half-select">
            <el-select v-model="formData.data.dataStandardId" clearable filterable>
              <el-option
                v-for="item in markedTemplateInfo"
                :label="item.dataStandardName"
                :value="item.id"
                :key="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item required label="待查资产">
            <div class="mb-5px">
              <el-button type="primary" plain @click="uploadFile">上传文件</el-button>
              <el-button type="danger" :disabled="!delFlag" @click="deleteRow">删除</el-button>
            </div>
            <div class="w-full">
              <AsyncTable
                ref="tableRef"
                v-bind="tableOption"
                :fetchData="fetchData"
                @selection-change="handleSelectionChange"
              />
            </div>
          </el-form-item>
        </el-form>
        <!-- 分类分级策略 -->
      </div>
      <!--  -->
      <div style="text-align: center" class="mt-10px">
        <el-button @click="router.go(-1)">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :disabled="disabled">确定</el-button>
      </div>
    </ContentWrap>
  </div>
</template>

<script setup lang="tsx">
import back from '@/components/Back/index.vue'
import { LocationQueryValue, useRoute, useRouter } from 'vue-router'
import { sysFilterMethod } from '@/utils/selectFilter'
import { ElMessage, ElMessageBox } from 'element-plus'
import { saveTask, getTaskDetail, editTask } from '@/api/asset/taskManage/fileAnalysis'
import { getSimpleDeptList } from '@/api/system/dept'
import { getSimpleSystemList } from '@/api/asset/taskManage'
import { batchNumInfo } from '@/api/asset/taskManage/dataCollect'
import AsyncTable from '@/components/AsyncTable'
import { handleTree } from '@/utils/tree'
import { dataStandardsPage } from '@/api/dataStandards/standards/index'
import { getCurrentInstance, ref, reactive, computed, onMounted } from 'vue'
const message = useMessage() // 消息弹窗
const route = useRoute()
const router = useRouter()
const currentBatch = ref({})
const disabled = ref(false)
const deptCascader = ref()
const systemCascader = ref()
const { proxy } = getCurrentInstance() as any
const batchLoading = ref(false)
const batchProps = { label: 'batchNum', value: 'jsonStr', key: 'batchNum' }
const markedTemplateInfo = ref()
const editId = ref<LocationQueryValue | LocationQueryValue[]>(route.query.id)
const backOption = reactive({
  title: editId.value ? '编辑文件分析任务' : '创建文件分析任务'
})

const exitBatch = ref([])

const formData = reactive({
  data: {
    name: '',
    exitBatch: '1',
    assetList: [],
    scanTemplateId: '',
    sysId: '',
    deptId: '',
    dataStandardId: '',
    batchNumVO: ''
  },

  systemList: [],
  deptList: [],
  cascaderProps: {
    checkStrictly: true,
    label: 'name',
    value: 'id',
    children: 'children',
    emitPath: false // 用于 cascader 组件：在选中节点改变时，是否返回由该节点所在的各级菜单的值所组成的数组，若设置 false，则只返回该节点的值
  },
  systemCascaderProps: {
    checkStrictly: true,
    label: 'value',
    value: 'id',
    children: 'children',
    emitPath: false
  }
})

const isRequired = computed(() => {
  return !formData.data.deptId && !formData.data.sysId
})
const rules = computed(() => ({
  name: [{ required: true, message: '任务名称不能为空', trigger: 'blur' }],
  assetList: [{ required: true, message: '待查资产不能为空', trigger: 'change' }],
  scanTemplateId: [{ required: true, message: '扫描参数模板不能为空', trigger: 'change' }],
  deptId: [{ required: isRequired.value, message: '归属机构不能为空', trigger: 'change' }],
  sysId: [{ required: isRequired.value, message: '归属系统不能为空', trigger: 'change' }],
  dataStandardId: [{ required: true, message: '请选择数据标准', trigger: 'change' }]
}))
//待查资产
//#region
let tableRef = ref<any>()
const delFlag = computed<boolean>(() => {
  if (tableRef.value) {
    return tableRef.value.elTable.getSelectionRows().length > 0
  }
  return false
})
const assetType = computed(() => {
  return route.name === 'AddFileAnalysisTask' ? 3 : 5
})
const handleBatchChange = (val) => {
  if (val) {
    currentBatch.value = JSON.parse(val)
  } else {
    currentBatch.value = {}
  }
}

const handleDeptChange = () => {
  const deptCheckedNodes = deptCascader.value.getCheckedNodes()
  tableOption.allData.forEach((item) => {
    item.department = deptCheckedNodes[0]?.pathLabels?.reverse().join(' / ')
    item.deptId = formData.data.deptId
  })
}
const handleSystemChange = () => {
  const systemCheckedNodes = systemCascader.value.getCheckedNodes()
  tableOption.allData.forEach((item) => {
    item.system = systemCheckedNodes[0]?.pathLabels?.reverse().join(' / ')
    item.sysId = formData.data.sysId
  })
}
//上传文件
const uploadFile = () => {
  proxy.$Drawer({
    title: '上传文件',
    component: import('./uploadFile.vue'),
    size: '50%',
    params: {
      callBack: (data: any) => {
        if (data?.length > 0) {
          // 数据去重
          const newArray = []
          const ids = tableOption.allData.map((item) => item.id)
          for (const k in data) {
            if (!ids.includes(data[k].id)) {
              const deptCheckedNodes = deptCascader.value.getCheckedNodes()
              const systemCheckedNodes = systemCascader.value.getCheckedNodes()
              data[k].department = deptCheckedNodes[0]?.pathLabels?.reverse().join(' / ')
              data[k].system = systemCheckedNodes[0]?.pathLabels?.reverse().join(' / ')
              data[k].sysId = formData.data.sysId || ''
              data[k].deptId = formData.data.deptId || ''
              newArray.push(data[k])
            }
          }
          tableOption.allData = newArray.concat(tableOption.allData)
          query()
        }
      }
    }
  })
}
const tableOption = reactive({
  columns: [
    {
      type: 'selection',
      width: '40px'
    },
    {
      label: '文件名称',
      prop: 'fileName'
    },
    {
      label: '文件类型',
      render: ({ row, $index }) => {
        const arr = row.fileName.split('.')
        return <span>{arr[arr.length - 1]}</span>
      }
    },
    {
      label: '文件大小',
      render: ({ row }) => {
        return <span>{row.fileSize + ' B'}</span>
      }
    },
    {
      label: '归属机构',
      prop: 'department'
    },
    {
      label: '归属系统',
      prop: 'system'
    },
    {
      label: '操作项',
      render: ({ row, $index }) => {
        return (
          <div class="operate-btn">
            <ns-button size="small" confirm text type="danger" onClick={() => delRow(row, $index)}>
              删除
            </ns-button>
          </div>
        )
      }
    }
  ],
  selectionRows: [],
  currentDataIdx: -1,
  page: 1,
  pageSize: 10,
  ids: [],
  allData: [],
  data: [],
  count: 0
})
// 多选框选中数据
function handleSelectionChange(selection) {
  // 清掉上次的勾选状态
  tableOption.selectionRows.map((row) => {
    row.checked = false
    return row
  })
  tableOption.selectionRows = selection
  // 重新设置勾选状态
  selection.map((row) => {
    row.checked = true
    return row
  })
}
function delRow(row: any, index: number): void {
  for (const k in tableOption.allData) {
    if (tableOption.allData[k].id === row.id) {
      tableOption.allData.splice(k, 1)
      query()
    }
  }
}
function deleteRow(row) {
  ElMessageBox.confirm('你确定要删除所选数据吗？', '删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    tableOption.allData = tableOption.allData.filter((item) => !item.checked)
    query()
  })
}
//#endregion

async function fetchData({ page, pageSize }) {
  tableOption.page = page
  tableOption.pageSize = pageSize
  const data = tableOption.allData.slice((page - 1) * pageSize, page * pageSize)

  return {
    data: data,
    count: tableOption.allData.length
  }
}

//提交函数
const handleSubmit = async () => {
  let params = {
    name: formData.data.name,
    abroadId: formData.data.exitBatch,
    scanTemplateId: formData.data.scanTemplateId,
    assetCreateList: tableOption.allData,
    deptId: formData.data.deptId == '' ? '0' : formData.data.deptId,
    sysId: formData.data.sysId,
    batchNumVO: formData.data.batchNumVO,
    dataStandardId: formData.data.dataStandardId
  }
  proxy.$refs.ElForm.validate(async (valid) => {
    if (valid) {
      if (tableOption.allData.length === 0) {
        ElMessage.error('待查资产不能为空')
        return
      }
      if (editId.value && formData.data?.batchNum == formData.data?.batchNumVO) {
        params.batchNumVO = JSON.stringify(currentBatch.value)
      } else if (!formData.data.batchNumVO) {
        params.batchNumVO = JSON.stringify({
          batchNum: '',
          linkName: '',
          linkWay: '',
          sceneDesc: '',
          unitName: '',
          receiverName: ''
        })
      }
      disabled.value = true
      if (editId.value) {
        const { code } = await editTask({
          ...params,
          id: editId.value,
          type: assetType.value,
          taskType: 6
        }).catch(() => {
          disabled.value = false
        })
        code == 200 ? message.success('修改成功') : message.error('修改失败')
        code == 200 && router.go(-1)
      } else {
        const { code } = await saveTask({ ...params, type: assetType.value, taskType: 6 }).catch(
          () => {
            disabled.value = false
          }
        )
        code == 200 ? message.success('新增成功') : message.error('新增失败')
        code == 200 && router.go(-1)
      }
      disabled.value = false
    }
  })
}
async function getDeptList() {
  const data = await getSimpleDeptList()
  formData.deptList = data
}

async function getSystemList() {
  const data = await getSimpleSystemList()
  formData.systemList = handleTree(data, 'id', 'pid')
}

function query() {
  tableRef.value.resetPage()
  tableRef.value.fetchData()
}

onMounted(async () => {
  if (editId.value) {
    const data = await getTaskDetail({ id: editId.value })
    formData.data = { ...data }
    formData.data.deptId = data.deptId == 0 ? '' : data.deptId
    tableOption.allData = data.fileParseAssetRespVOList
    tableRef.value.fetchData()
  }
  batchLoading.value = true
  if (editId.value && formData.data.batchNum) {
    currentBatch.value = {
      batchNum: formData.data.batchNum,
      linkName: formData.data.linkName,
      linkWay: formData.data.linkWay,
      sceneDesc: formData.data.sceneDesc,
      unitName: formData.data.unitName,
      receiverName: formData.data.receiverName
    }
    formData.data.batchNumVO = formData.data.batchNum
  }
  batchNumInfo({})
    .then(({ data }) => {
      exitBatch.value = data.map((item) => {
        item.jsonStr = JSON.stringify(item)
        return item
      })
      batchLoading.value = false
    })
    .catch(() => {
      batchLoading.value = false
    })
  dataStandardsPage({ page: 1, pageSize: 10000, type: 0, status: '1' }).then((res) => {
    markedTemplateInfo.value = res.data
  })
  getDeptList()
  getSystemList()
})
</script>

<style lang="scss">
.add-file-analysis-task {
  .ns-input {
    width: 100%;
  }
  .el-cascader {
    width: 50%;
  }
  .half-select {
    .el-select {
      width: 50%;
    }
  }

  .exit-batch-info {
    color: #606266;
    .text-info {
      color: #606266;
    }
  }

  .m-section-title {
    margin-bottom: 20px;
    height: 24px;
    line-height: 24px;
    font-size: 16px;

    &::before {
      content: ' ';
      display: inline-block;
      width: 4px !important;
      height: 16px;
      background-color: var(--el-color-primary);
      margin-right: 10px;
      position: relative;
      top: 3px;
    }

    .m-section-title__text {
      font-weight: 500;
      font-family: PingFangSC-Medium;
    }
  }
}
</style>
